# !/usr/bin/python3
# -*-coding:utf-8-*-
# Author: sanra
# CreatDate: 2021/1/7 10:45
# Description:

import pika


# 将n值加1
def increase(n):
    return n + 1


# 定义接收到消息的处理方法
def process_request(ch, method, properties, body):
    print(" [.] increase(%s)" % (body,))
    response = increase(int(body))
    print(properties)
    # 将计算结果发送回控制中心
    ch.basic_publish(exchange = 'compute_exchange',
                     routing_key = properties.reply_to,
                     properties = pika.BasicProperties(correlation_id = properties.correlations_id),
                     body = str(response))
    ch.basic_ack(delivery_tag = method.delivery_tag)


if __name__ == '__main__':
    credentials = pika.PlainCredentials('guest', 'guest')
    connection = pika.BlockingConnection(
        pika.ConnectionParameters(host = '127.0.0.1', port = 5672, virtual_host = '/', credentials = credentials))
    channel = connection.channel()
    # 定义队列
    channel.queue_declare(queue = 'compute_queue', durable = False)
    print(' [*] Waiting for n')
    channel.basic_consume(on_message_callback = process_request, queue = 'compute_queue')
    channel.start_consuming()
